package shop.milvus.ServiceImpl;

import io.milvus.client.MilvusClient;
import io.milvus.grpc.*;
import io.milvus.param.MetricType;
import io.milvus.param.R;
import io.milvus.param.collection.*;
import io.milvus.param.dml.DeleteParam;
import io.milvus.param.dml.InsertParam;
import io.milvus.param.dml.SearchParam;
import io.milvus.response.SearchResultsWrapper;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Deprecated
public class MilvusServiceImpl1   {


    public final MilvusClient client;
    public MilvusServiceImpl1(MilvusClient client) {
        this.client = client;

    }

    public MilvusClient getClient(){
        return client;
    }

    public void createCollection( ) {
        String collectionName = "example_collection";

        FieldType idField = FieldType.newBuilder()
                .withName("id")
                .withDataType(DataType.Int64)
                .withPrimaryKey(true)
                .withAutoID(true)
                .build();

        FieldType vectorField = FieldType.newBuilder()
                .withName("embedding")
                .withDataType(DataType.FloatVector)
                .withDimension(128) // 向量维度
                .build();

        CreateCollectionParam createCollectionReq = CreateCollectionParam.newBuilder()
                .withCollectionName(collectionName)
                .withDescription("Example collection for Java")
                .withShardsNum(2)
                .addFieldType(idField)
                .addFieldType(vectorField)
                .build();

        client.createCollection(createCollectionReq);
        System.out.println("Collection created!");
    }



    public void insertData() {


        List<List<Float>> vectors = new ArrayList<>();
        vectors.add(randomVector(128));

        InsertParam insertParam = InsertParam.newBuilder()
                .withCollectionName("example_collection")
                .withFields(Arrays.asList(new InsertParam.Field("embedding", vectors)))
                .build();

        R<MutationResult> insertResult = client.insert(insertParam);
        System.out.println("Insert result: " + insertResult);


    }

    // 随机生成一个 128 维向量
    private List<Float> randomVector(int dim) {
        Random rand = new Random();
        List<Float> vector = new ArrayList<>();
        for (int i = 0; i < dim; i++) {
            vector.add(rand.nextFloat());
        }
        return vector;
    }
    public void searchVectors() {
        String collectionName = "example_collection";

        // 待搜索向量

        List<Float> queryVectors = new ArrayList<>();
        double[]queryVectors1=new double[]{0.8033967018127441,0.8121124505996704,-0.051090873777866364,-0.6719133257865906,0.9314159750938416,0.8679242730140686,0.7973452210426331,-0.024703798815608025,0.5272630453109741,0.27758103609085083,-0.8305146098136902,-0.8453351855278015,0.1450418084859848,0.565788209438324,-0.15054695308208466,0.9307773113250732,-0.9471458792686462,-0.07269663363695145,-0.3479999303817749,-0.47921743988990784,0.32273900508880615,0.7166264653205872,-0.28319838643074036,0.7179522514343262,0.003746896516531706,0.9987159967422485,0.2088044285774231,-0.9515088200569153,0.1889396756887436,-0.1776776909828186,0.620186448097229,-0.14606645703315735,-0.5592348575592041,-0.9993702173233032,-0.33244654536247253,-0.35513415932655334,0.4337594509124756,0.5895105600357056,0.5946143865585327,0.6544253826141357,-0.8052107095718384,0.9998885989189148,0.7576771974563599,0.2601729929447174,0.09048066288232803,0.8249669671058655,0.0819256454706192,0.7096243500709534,-0.9862684607505798,-0.25987720489501953,0.4920588731765747,0.9154441952705383,-0.2904440462589264,0.6220715045928955,-0.8245762586593628,0.8821633458137512,-0.5246170163154602,0.7599638104438782,-0.34623005986213684,-0.35322967171669006,-0.8580427765846252,-0.47694772481918335,-0.7878243327140808,0.9426982998847961,0.36924952268600464,-0.11970863491296768,-0.5614506602287292,0.1285472810268402,-0.21115344762802124,-0.8430145978927612,-0.43503472208976746,-0.9545015096664429,0.3329048156738281,0.8917953372001648,0.39503899216651917,0.8046366572380066,0.3645748496055603,0.6552407145500183,-0.8359552025794983,-0.013186180964112282,-0.6816601753234863,-0.7736166715621948,0.2847338616847992,-0.4238884449005127,0.9249840974807739,0.9561656713485718,-0.5094842910766602,0.19420717656612396,0.38396120071411133,-0.20371529459953308,0.8694877028465271,-0.985489010810852,-0.8489218354225159,0.05085276439785957,-0.9787139296531677,-0.5033889412879944,-0.892591655254364,-0.39747709035873413,0.6133314371109009,0.961657702922821,0.8209514617919922,-0.11595837771892548,-0.281413197517395,-0.15143050253391266,-0.3431413173675537,-0.9817984104156494,0.44853898882865906,-0.771738588809967,-0.3973359763622284,-0.8437689542770386,-0.35599255561828613,-0.5660797953605652,0.5998610854148865,0.49271970987319946,0.5880980491638184,-0.894061267375946,0.15271992981433868,-0.5547081828117371,-0.9210208654403687,0.21532690525054932,0.20113630592823029,0.7036765813827515,0.7689694762229919,-0.39400044083595276,-0.6577625274658203,0.40838634967803955,0.05874239653348923,0.9738600850105286}; // 128维
        for (double queryVector : queryVectors1) {
            queryVectors.add((float)queryVector);
        }
        List<List<Float>> vector = new ArrayList<>();
        vector.add(queryVectors);
        // 设置搜索参数
        SearchParam searchParam = SearchParam.newBuilder()
                .withCollectionName(collectionName)
                .withVectorFieldName("embedding")
                .withTopK(5) // 返回最相似的前5条
                .withVectors(vector)
                .withMetricType(MetricType.COSINE) // 内积/余弦相似度
                .withParams("{\"nprobe\":10}") // 可选
                .build();


        R<SearchResults> results = client.search(searchParam);
        SearchResults data = results.getData();
        SearchResultData results1 = data.getResults();
        SearchResultsWrapper wrapper = new SearchResultsWrapper(results1);

        // 获取 topK 的 ID 和分数
        // 遍历每一行（每个 query 的 topK）
//        for (int i = 0; i < wrapper.getRowRecords().size(); i++) {
            List<SearchResultsWrapper.IDScore> idScores = wrapper.getIDScore(0);

            List<Long> ids = new ArrayList<>();
            List<Float> scores = new ArrayList<>();

            for (SearchResultsWrapper.IDScore idScore : idScores) {
                ids.add(idScore.getLongID());      // 如果是 String ID 用 idScore.getStrID()
                scores.add(idScore.getScore());
            }

            System.out.println("Result " +1 + ": IDs = " + ids + ", Scores = " + scores);
//        }

    }


    public void showDetails() {
        // 1. 检查集合是否存在
        R<Boolean> exampleCollection = client.hasCollection(HasCollectionParam.newBuilder()
                .withCollectionName("example_collection")
                .withDatabaseName("default") // 👈 保证和 Insight 一致
                .build());

// 2. 加载集合
//        client.loadCollection(LoadCollectionParam.newBuilder()
//                .withCollectionName("example_collection")
//                .build());
//
//// 3. 检查集合 row 数量
//        GetCollectionStatisticsResponse exampleCollection = client.getCollectionStatistics(
//                GetCollectionStatisticsParam.newBuilder()
//                        .withCollectionName("example_collection")
//                        .build()
//        ).getData();

        System.out.println("Row count = " + exampleCollection);

    }


    public void deleteData() {
        List<Long> idsToDelete = Arrays.asList(123L, 456L, 789L);

        DeleteParam deleteParam = DeleteParam.newBuilder()
                .withCollectionName("example_collection") // 你的 collection 名字
                .withExpr("id in [460415814256539236,460415814256539239]")     // 用表达式指定删除条件
                .build();

        R<MutationResult> response = client.delete(deleteParam);

        if (response.getStatus() == R.Status.Success.getCode()) {
            System.out.println("删除成功");
        } else {
            System.err.println("删除失败: " + response.getMessage());
        }
    }


}
